package item.lxp.Util;


import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Iterator;
import java.util.Set;

import javax.validation.groups.Default;

public class ValidatorUtil {

    private static Validator validator = Validation.buildDefaultValidatorFactory()
            .getValidator();

//    @Autowired
//    public static Validator validator;  不能注入或者说框架没有将Validator自动注入


    public static <T> void validate(T obj) {


        Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj,Default.class);
        //抛出检验异常
        Iterator<ConstraintViolation<T>> iter = constraintViolations.iterator();
        while (iter.hasNext()) {
            ConstraintViolation<T> error = iter.next();
            StringBuffer buffer = new StringBuffer().append("[")
                    .append(error.getPropertyPath().toString()).append("]")
                    .append(error.getMessage());
            throw new RuntimeException(buffer.toString());
        }

    }

}
